import {
  ChangeEvent,
  useEffect,
  forwardRef,
  useImperativeHandle,
  ForwardedRef,
  useCallback,
  useMemo,
  useRef,
  useState
} from 'react';
import { Button, Checkbox, Form, Input, InputNumber, message, Select, Switch, Collapse } from 'antd';
import { DownloadOutlined, PlusOutlined, InfoCircleOutlined } from '@ant-design/icons';
import { getMessage, TextWidget } from '@inbiz/react';
import { getPlatform, getExtByFileName } from '@inbiz/utils';
import MultilingualInput from '@inbiz/basic/MultilingualInput';
import SortFieldDesc from './SortFieldDesc';
import { AddField, IAddField, IField } from './addField';
import Editable from './editTable';
import { TemplateStr } from './Template.jsx';
import { initValue, initFileSearchField, initFolderSearchField, fileDefaultField, folderDefaultField } from './utils'
import jgmb from '../svg/jgmb.svg';
import { IIndexData, UpdateTemplateFile } from '../service';

const { Option } = Select;
const { Panel } = Collapse;

export type IConfig = IIndexData & {
  title: string; // 标题
  defaultSearchCriteria?: string; //默认搜索条件
  resultsSearchCriteria?: string; //结果搜索条件
  section: boolean; //切面
  sectionDisplayPosition: 'top' | 'left' | 'right';
  sectionType?: 'default' | 'custom',// 移动端切面显示类型 
  sectionTemplate?: { // 移动端切面模板
    //自定义模板
    name: string;
    content: string;
  }
  sectionNumber: number; // 切面数量
  sectionWidth: number; // 切面显示宽度
  leftSectionWidth: number,
  rightSectionWidth: number,
  highlightField?: IField[]; // 高亮字段
  showStyle: 'list' | 'thumbnail' | 'bigthumbnail'; // 显示风格(列表、缩略图)
  searchField?: IField[]; // 模糊搜索字段
  vagueSearchField?: IField[]; // 精确搜索字段
  excludeField?: IField[]; // 排除字段
  sortField?: ISortField[]; // 排序字段
  uniqueField?: [IField]; // 唯一标识字段
  checkbox: boolean; // 选择框
  columnType: 'list' | 'custom'; // 显示风格列项、自定义
  columnField: IField[]; // 列项字段
  template: {
    //自定义模板
    name: string;
    content: string;
  };
  showSystem: boolean; // 显示系统分类
  tabTitle?: string;
};

type ISortField = {
  sort: 'desc' | 'asc';
  enable: boolean;
  default?: boolean; // 默认排序字段(匹配度)
} & IField;

export type IConfigRef = {
  getValue: () => IConfig;
};
const showTypeSort = ['integer', 'long', 'keyword', 'date'];
function ConfigDetail(props: { config: IConfig; appId: string }, ref: ForwardedRef<IConfigRef>) {
  const [form] = Form.useForm();
  const section = Form.useWatch('section', form);
  const sectionDisplayPosition = Form.useWatch('sectionDisplayPosition', form);
  const sortField = Form.useWatch('sortField', form) as ISortField[];
  const columnType = Form.useWatch('columnType', form);
  const checkbox = Form.useWatch('checkbox', form);
  const sectionType = Form.useWatch('sectionType', form)
  const [sortVisible, $sortVisible] = useState(false)
  const [selectRecord, $selectRecord] = useState({})
  useImperativeHandle(
    ref,
    () => ({
      getValue: () => {
        return {
          ...props.config,
          ...form.getFieldsValue(),
        };
      },
    }),
    [props.config.tabTitle],
  );

  // 排序字段详情配置
  const handleSortChange = useCallback(
    (
      options:
        | {
          IndexFieldName: string;
          field?: string;
          value?: unknown;
          type?: 'update' | 'delete' | 'add';
        }
        | ISortField[],
    ) => {
      if (!Array.isArray(options)) {
        const { IndexFieldName, field, value, type = 'update' } = options;
        const sortField = form.getFieldsValue(['sortField']).sortField as ISortField[];
        if (type === 'update') {
          const data = sortField.find((item) => item.IndexFieldName === IndexFieldName)!;
          data[field!] = value;
        }
        if (type === 'delete') {
          const index = sortField.findIndex((item) => item.IndexFieldName === IndexFieldName);
          sortField.splice(index, 1);
        }

        form.setFieldsValue({
          sortField: [...sortField],
        });
      } else {
        form.setFieldsValue({
          sortField: options,
        });
      }
    },
    [],
  );
  const sortFieldColumns = useMemo(() => {
    return [
      {
        title: getMessage('SearchResultEngine.fieldName'),
        dataIndex: 'IndexFieldName',
        width: 140,
      },
      {
        title: getMessage('SearchResultEngine.fieldDescription'),
        dataIndex: 'IndexFieldDesc',
        width: 170,
        render: (value: string, record: ISortField) => {
          return (
            <MultilingualInput
              placeholder={getMessage('SearchResultEngine.pleaseEnterTheContent')}
              value={value}
              bordered={false}
              onChange={(newValue: string) => {
                if (newValue?.indexOf('{multilingual}') === 0 || newValue == '') {
                  handleSortChange({
                    IndexFieldName: record.IndexFieldName,
                    field: 'IndexFieldDesc',
                    value: newValue,
                  });
                }
              }}
              onBlur={(newValue: string) => {
                if (value === newValue) {
                  return;
                }
                handleSortChange({
                  IndexFieldName: record.IndexFieldName,
                  field: 'IndexFieldDesc',
                  value: newValue,
                });
              }}
            />
          );
        },
      },
      {
        title: getMessage('SearchResultEngine.fieldOrder'),
        dataIndex: 'sort',
        width: 170,
        render: (value: string, record: ISortField) => {
          if (getPlatform() === 'web') {
            return <span
              style={{ cursor: 'pointer' }}
              onClick={() => {
                $selectRecord({ ...record, value })
                $sortVisible(true)
              }}>
              {value == 'asc' || value.sort == 'asc' ? getMessage('SearchResultEngine.ascendingOrder') : getMessage('SearchResultEngine.descendingOrder')}
            </span>
          } else {
            return (
              <Select
                value={value.sort ?? value}
                bordered={false}
                style={{ width: '100%' }}
                options={[
                  { label: getMessage('SearchResultEngine.ascendingOrder'), value: 'asc' },
                  { label: getMessage('SearchResultEngine.descendingOrder'), value: 'desc' },
                ]}
                onChange={(value) =>
                  handleSortChange({
                    IndexFieldName: record.IndexFieldName,
                    field: 'sort',
                    value: value || value.sort,
                  })
                }
              />
            );
          }
        },
      },
      {
        title: getMessage('SearchResultEngine.enable'),
        dataIndex: 'enable',
        width: 100,
        render: (value: boolean, record: ISortField) => {

          return (
            <Checkbox
              checked={value}
              onChange={(value) =>
                handleSortChange({
                  IndexFieldName: record.IndexFieldName,
                  field: 'enable',
                  value: value.target.checked,
                })
              }
            />
          );
        },
      },
    ];
  }, []);

  const getConfigKeyValue = (configKey: keyof IConfig, config: IConfig, fileDefaultValue: any, folderDefaultValue: any) => {
    let configValue = config[configKey]
    if (!configValue && config.IndexCode == 'file') {
      configValue = fileDefaultValue
    } else if (!configValue && config.IndexCode == 'folder') {
      configValue = folderDefaultValue
    }
    return configValue
  }

  useEffect(() => {
    form.resetFields();
    const config = {
      sectionType: 'default',
      sectionTemplate: {
        name: 'section.jsx',
        content: InbizConfig.PUBLIC_PATH + '/template_mobile/section.jsx',
      },
      ...props.config
    } as IConfig;
    const columnField = getConfigKeyValue('columnField', config, fileDefaultField(), folderDefaultField())
    const searchField = getConfigKeyValue('searchField', config, initFileSearchField, initFolderSearchField)
    const vagueSearchField = getConfigKeyValue('vagueSearchField', config, initFileSearchField, initFolderSearchField)
    if (!config.template && (config.IndexCode === '_document_' || config.IndexCode === 'file' || config.IndexCode === 'folder')) {
      if (config.IndexName === 'folder') {
        if (getPlatform() === 'web') {
          config.template = {
            name: 'folder.jsx',
            content: InbizConfig.PUBLIC_PATH + '/template/folder.jsx',
          };
        } else {
          config.template = {
            name: 'folder.jsx',
            content: InbizConfig.PUBLIC_PATH + '/template_mobile/folder.jsx',
          };
        }

      } else if (config.IndexName === 'file') {
        if (getPlatform() === 'web') {
          config.template = {
            name: 'file.jsx',
            content: InbizConfig.PUBLIC_PATH + '/template/file.jsx',
          };
        } else {
          config.template = {
            name: 'file.jsx',
            content: InbizConfig.PUBLIC_PATH + '/template_mobile/file.jsx',
          };
        }
      }
    }
    let resultsSearchCriteria = ''
    if (config.indexName == 'file' || config.IndexName == 'file') {
      resultsSearchCriteria = `(filepath:(1 OR 2 OR 7) OR masterfilepath:(1 OR 2 OR 7))`
    } else if (config.indexName == 'folder' || config.IndexName == 'folder') {
      resultsSearchCriteria = `folderpath:(1 OR 2 OR 7)`
    }
    form.setFieldsValue({
      resultsSearchCriteria,
      ...initValue(),
      ...config,
      searchField,
      vagueSearchField,
      indexName: config.indexName || config.IndexName,
      columnField,
    });
  }, [props.config]);

  useEffect(() => {
    const config = { ...props.config };
    if (sectionDisplayPosition == 'left' || sectionDisplayPosition == 'right') {

      form.setFieldsValue({
        leftSectionWidth: config.leftSectionWidth ? config.leftSectionWidth : 200,
        rightSectionWidth: config.rightSectionWidth ? config.rightSectionWidth : 320,
        sectionWidth: config.sectionWidth ? config.sectionWidth : 200
      })
    }
  }, [sectionDisplayPosition])

  const options = useMemo(() => {
    if (props.config.IndexName == 'file') {
      return [
        { label: getMessage('SearchResultEngine.belongCategory'), value: 'belongCategory' },
        { label: getMessage('SearchResultEngine.matchtype'), value: 'matchtype' },
        { label: getMessage('SearchResultEngine.sourceUser'), value: 'sourceUser' },
        { label: getMessage('SearchResultEngine.authorityFilter'), value: 'authorityFilter' },
      ]
    } else if (props.config.IndexName == 'folder') {
      return [
        { label: getMessage('SearchResultEngine.belongCategory'), value: 'belongCategory' },
        { label: getMessage('SearchResultEngine.sourceUser'), value: 'sourceUser' },
        { label: getMessage('SearchResultEngine.authorityFilter'), value: 'authorityFilter' },
      ]
    }
    return []
  }, [props.config])
  return (
    <>
      <Form form={form} labelAlign="left" className="configDetail" >
        <Form.Item
          label={getMessage('SearchResultEngine.titleField')}
          name="indexName"
          rules={[
            { required: true, message: getMessage('SearchResultEngine.titleCannotBeEmpty') },
          ]}
        >
          <MultilingualInput />
        </Form.Item>


        <Collapse
          defaultActiveKey={['1']}
          bordered={false}
          expandIconPosition='end'
        >
          <Panel header={getMessage('SearchResultEngine.conditionConfiguration')} key='1'>
            <Form.Item
              label={getMessage('SearchResultEngine.defaultSearchCriteria')}
              name="defaultSearchCriteria"
            >
              <Input />
            </Form.Item>

            <Form.Item
              label={getMessage('SearchResultEngine.resultsSearchCriteria')}
              name="resultsSearchCriteria"
              tooltip={{
                title: getMessage('SearchResultEngine.resultsSearchCriteriaTips'),
                icon: <InfoCircleOutlined />,
              }}
            >
              <Input />
            </Form.Item>
            {props.config.IndexType == 3 && (
              <Form.Item
                label={getMessage('SearchResultEngine.displaySystemClassification')}
                name="showSystem"
                valuePropName="checked"
              >
                <Switch />
              </Form.Item>
            )}

            <Form.Item name="highlightField" label={getMessage('SearchResultEngine.highlightField')}>
              <AddField
                indexName={props.config.IndexName}
                title={getMessage('SearchResultEngine.addField')}
                modelTitle={getMessage('SearchResultEngine.addHighlightedField')}
              />
            </Form.Item>

            <Form.Item name="searchField" label={getMessage('SearchResultEngine.fuzzySearchField')}>
              <AddField
                indexName={props.config.IndexName}
                title={getMessage('SearchResultEngine.addField')}
                modelTitle={getMessage('SearchResultEngine.addFuzzySearchField')}
              />
            </Form.Item>

            <Form.Item
              name="vagueSearchField"
              label={getMessage('SearchResultEngine.preciseSearchField')}
            >
              <AddField
                indexName={props.config.IndexName}
                title={getMessage('SearchResultEngine.addField')}
                modelTitle={getMessage('SearchResultEngine.addPreciseSearchField')}
              />
            </Form.Item>

            <Form.Item name="excludeField" label={getMessage('SearchResultEngine.excludeFields')}>
              <AddField
                indexName={props.config.IndexName}
                title={getMessage('SearchResultEngine.addField')}
                modelTitle={getMessage('SearchResultEngine.addExcludeField')}
              />
            </Form.Item>
          </Panel>
        </Collapse>

        <Collapse
          defaultActiveKey={['2']}
          bordered={false}
          expandIconPosition='end'
        >
          <Panel header={getMessage('SearchResultEngine.sectionConfiguration')} key='2'>
            <Form.Item
              label={getMessage('SearchResultEngine.sectionDisplay')}
              name="section"
              valuePropName="checked"
            >
              <Switch />
            </Form.Item>
            {section && getPlatform() === 'web' && (
              <Form.Item
                name="sectionDisplayPosition"
                label={getMessage('SearchResultEngine.sectionDisplayPosition')}
              >
                <Select>
                  <Option value="top">
                    <TextWidget>SearchResultEngine.top</TextWidget>
                  </Option>
                  <Option value="left">
                    <TextWidget>SearchResultEngine.left</TextWidget>
                  </Option>
                  <Option value="right">
                    <TextWidget>SearchResultEngine.right</TextWidget>
                  </Option>
                </Select>
              </Form.Item>
            )}
            {
              section && getPlatform() === 'wap' && <>
                <Form.Item
                  name="sectionType"
                  label="切面配置"
                >
                  <Select>
                    <Option value="default"> 默认</Option>
                    <Option value="custom">自定义</Option>
                  </Select>
                </Form.Item>
                {
                  sectionType === 'custom' && <Form.Item name="sectionTemplate">
                    <Template appId={props.appId} defaultTemplate={{
                      name: 'sectionTemplate.jsx',
                      content: InbizConfig.PUBLIC_PATH + '/template_mobile/section.jsx',
                    }} />
                  </Form.Item>
                }
              </>
            }


            {section &&
              getPlatform() === 'web' &&
              (sectionDisplayPosition !== 'top' ? (
                <Form.Item
                  label={getMessage('SearchResultEngine.displayWidth')}
                  name={sectionDisplayPosition == 'left' ? "leftSectionWidth" : 'rightSectionWidth'}
                >
                  <InputNumber />
                </Form.Item>
              ) : (
                <Form.Item name="sectionNumber" label={getMessage('SearchResultEngine.numberOfSections')}>
                  <InputNumber min={1} max={10} />
                </Form.Item>
              ))}

            {sectionDisplayPosition == 'right' && <Form.Item
              label={getMessage('SearchResultEngine.showSectionIcon')}
              name="showSectionIcon"
              valuePropName="checked"
            >
              <Switch />
            </Form.Item>}
            {sectionDisplayPosition == 'right' && <Form.Item
              label={getMessage('SearchResultEngine.showfilterNumber')}
              name="showfilterNumber"
              valuePropName="checked"
            >
              <Switch />
            </Form.Item>}

            {getPlatform() === 'web' && sectionDisplayPosition == 'right' &&options.length > 0 &&
              <Form.Item
                label={getMessage('SearchResultEngine.showContents')}
                name="showContents"
              >
                <Checkbox.Group options={options} />
              </Form.Item>
            }
          </Panel>
        </Collapse>

        {/* {getPlatform() === 'web' &&
        (props.config.IndexName == 'file' || props.config.IndexName == 'folder') && (
          <Form.Item name="showStyle" label={getMessage('SearchResultEngine.displayStyle')}>
            <Select>
              <Option value="list">
                <TextWidget>SearchResultEngine.list</TextWidget>
              </Option>
              <Option value="thumbnail">
                <TextWidget>SearchResultEngine.thumbnail</TextWidget>
              </Option>
              <Option value="bigthumbnail">
                <TextWidget>SearchResultEngine.bigthumbnail</TextWidget>
              </Option>
            </Select>
          </Form.Item>
        )} */}

        <Collapse
          defaultActiveKey={['3']}
          bordered={false}
          expandIconPosition='end'
        >
          <Panel header={getMessage('SearchResultEngine.sortField')} key='3'>
            <Form.Item name="sortField" label={getMessage('SearchResultEngine.sortField')}>
              <AddField
                disabledCheckbox
                indexName={props.config.IndexName}
                modelTitle={getMessage('SearchResultEngine.addSortField')}
                title={getMessage('SearchResultEngine.addField')}
                showList={false}
                showType={showTypeSort}
                beforeChange={(value) =>
                  value?.map((item) => {
                    return { ...item, enable: true, sort: item.sort || { sort: 'desc' } } as unknown as (typeof value)[number];
                  })
                }
              />
            </Form.Item>
            {sortField && !!sortField.length && (
              <Editable
                rowKey="IndexFieldName"
                value={sortField || []}
                onChange={handleSortChange}
                columns={sortFieldColumns}
              />
            )}
          </Panel>
        </Collapse>

        <Collapse
          defaultActiveKey={['4']}
          bordered={false}
          expandIconPosition='end'
        >
          <Panel header={getMessage('SearchResultEngine.searchResultConfiguration')} key='4'>
            <Form.Item
              label={getMessage('SearchResultEngine.viewmode')}
              name="showStyle"
            >
              <Select>
                <Option key='list'>
                  <TextWidget>SearchResultEngine.list</TextWidget>
                </Option>
                <Option key='thumbnail'>
                  <TextWidget>SearchResultEngine.thumbnail</TextWidget>
                </Option>
                <Option key='bigthumbnail'>
                  <TextWidget>SearchResultEngine.bigthumbnail</TextWidget>
                </Option>
              </Select>
            </Form.Item>
            <Form.Item
              label={getMessage('SearchResultEngine.checkBox')}
              name="checkbox"
              valuePropName="checked"
            >
              <Switch />
            </Form.Item>
            {checkbox && (
              <Form.Item
                label={getMessage('SearchResultEngine.uniqueIdentification')}
                name="uniqueField"
                tooltip={{
                  title: getMessage('SearchResultEngine.uniqueFieldTip'),
                  icon: <InfoCircleOutlined />,
                }}
              >
                <AddField
                  selectionType="radio"
                  showList={false}
                  indexName={props.config.IndexName}
                  modelTitle={getMessage('SearchResultEngine.selectUniqueId')}
                  title={({ onOpen, value }) => (
                    <Input readOnly onClick={onOpen} value={value?.[0]?.IndexFieldName} />
                  )}
                />
              </Form.Item>
            )}
            <Form.Item name="columnType" label={getMessage('SearchResultEngine.columnItemConfiguration')}>
              <Select>
                <Option value="list">
                  <TextWidget>SearchResultEngine.itemized</TextWidget>
                </Option>
                <Option value="custom">
                  <TextWidget>SearchResultEngine.custom</TextWidget>
                </Option>
              </Select>
            </Form.Item>

            {columnType === 'list' ? (
              <Form.Item name="columnField">
                <ColumnField indexName={props.config.IndexName} />
              </Form.Item>
            ) : (
              <Form.Item name="template">
                <Template appId={props.appId} />
              </Form.Item>
            )}
          </Panel>
        </Collapse>
      </Form>

      <SortFieldDesc
        sortVisible={sortVisible}
        $sortVisible={$sortVisible}
        handleSortChange={handleSortChange}
        selectRecord={selectRecord}
      />
    </>
  );
}

export default forwardRef(ConfigDetail);

// 列项字段 表格
function ColumnField<T extends IField>({
  value,
  onChange,
  indexName,
}: {
  value?: T[];
  onChange?: (value: T[]) => void;
  indexName: string;
}) {
  const addRef = useRef<IAddField>(null);
  const valueRef = useRef(value || []);
  const columns = useMemo(() => {
    return [
      {
        title: getMessage('SearchResultEngine.fieldName'),
        dataIndex: 'IndexFieldName',
        width: 200,
        ellipsis: true
      },
      {
        title: getMessage('SearchResultEngine.fieldDescription'),
        dataIndex: 'IndexFieldDesc',
        width: 200,
        ellipsis: true,
        render: (value: string, record: T) => {
          return (
            <MultilingualInput
              placeholder={getMessage('SearchResultEngine.pleaseEnterTheContent')}
              value={value}
              bordered={false}
              onChange={(newValue: string) => {
                if (newValue?.indexOf('{multilingual}') === 0) {
                  handleChange({
                    ...record,
                    IndexFieldDesc: newValue,
                    type: 'update',
                  });
                }
              }}
              onBlur={(newValue: string) => {
                if (value === newValue) {
                  return;
                }
                handleChange({
                  ...record,
                  IndexFieldDesc: newValue,
                  type: 'update',
                });
              }}
            />
          );
        },
      },
    ];
  }, []);
  useEffect(() => {
    valueRef.current = value || [];
  }, [value]);
  const handleChange = useCallback(
    (list: T[] | { type: 'add' | 'delete' | 'update'; IndexFieldName: string }) => {
      if (Array.isArray(list)) {
        onChange?.(list);
      } else {
        if (list.type == 'delete' || list.type == 'update') {
          const index = valueRef.current.findIndex(
            (item) => item.IndexFieldName === list.IndexFieldName,
          );
          const newValue = [...valueRef.current];
          if (list.type == 'delete') {
            newValue.splice(index, 1);
          } else {
            newValue[index] = {
              ...newValue[index],
              ...list,
            };
            delete newValue[index]['type'];
          }
          onChange?.(newValue);
        }
      }
    },
    [onChange],
  );
  const footer = useCallback(() => {
    return (
      <div className="columnField-add">
        <span onClick={() => addRef.current?.show()}>
          <PlusOutlined /> <TextWidget>SearchResultEngine.addField</TextWidget>
        </span>
      </div>
    );
  }, [onChange]);
  return (
    <>
      <Editable
        rowKey="IndexFieldName"
        value={value || []}
        columns={columns}
        onChange={handleChange}
        footer={footer}
      />
      <AddField
        ref={addRef}
        value={value}
        onChange={handleChange as (value: IField[]) => void}
        indexName={indexName}
        modelTitle={getMessage('SearchResultEngine.addColumnItemField')}
        showList={false}
      />
    </>
  );
}

// 模板
function Template<
  T extends {
    name: string;
    content: string;
  },
>({ value, onChange, appId, defaultTemplate }: { value?: T; appId: string; defaultTemplate?: T; onChange?: (value: T) => void }) {
  const inputRef = useRef<HTMLInputElement>(null);
  // 下载模板
  const onDownloadTemplate = useCallback(
    (isDefault?: boolean) => {
      let name = value?.name,
        content = value?.content;
      if (isDefault) {
        if (defaultTemplate) {
          name = defaultTemplate.name
          content = defaultTemplate.content
        } else {
          // 下载初始模板
          name = 'Template.jsx';
          content = TemplateStr;
        }
      }
      let aLink = document.createElement('a');
      aLink.download = name!;
      if (content?.includes('/inbiz/static/' + appId)) {
        aLink.href = content + '?raw';
      } else {
        if (content?.includes('/template')) {
          if (!content.includes('/inbiz')) {
            content = InbizConfig.PUBLIC_PATH + content;
          }
          aLink.href = content.replace('.jsx', '_origin.jsx').replace(
            '//',
            '/',
          );
        } else {
          aLink.href = URL.createObjectURL(new Blob([content!]));
        }
      }
      document.body.appendChild(aLink);
      aLink.click();
      aLink.remove();
    },
    [value],
  );
  // const isUploadUrl = useMemo(() => {
  //   return value?.content.indexOf('/inbiz/') === 0 || value?.content.indexOf('/template/') === 0;
  // }, [value?.content]);
  // 导入模板
  const onUploadTemplate = useCallback(
    (event: ChangeEvent<HTMLInputElement>) => {
      let file = event.target.files?.[0]; //获取文件对象
      //检测是否是拖拽文件到页面的操作

      if (file) {

        const fileextname = getExtByFileName(file.name)
        if (fileextname !== '.jsx') {
          return message.error(
            '更新失败！只能上传后缀为.jsx的文件',
          )
        }
        UpdateTemplateFile(appId, file)
          .then((res) => {
            onChange?.({
              name: res.fileName,
              content: res.path,
            } as T);
            value?.name ? message.success('更新成功') : message.success('导入成功');
          })
          .catch((e) => {
            value?.name
              ? message.error(
                '更新失败！只能上传后缀为.jsx的文件',
              )
              : message.error(
                '导入失败！只能上传后缀为.jsx的文件',
              );
          });
      }
    },
    [onChange],
  );

  return (
    <div className="templateBox">
      <Button type="primary" onClick={() => onDownloadTemplate(true)}>
        <TextWidget>SearchResultEngine.downloadTemplate</TextWidget>
      </Button>
      <Button type="primary" onClick={(e) => inputRef.current?.click()} style={{ marginLeft: 15 }}>
        <TextWidget>
          {value?.name ? 'SearchResultEngine.updateTemplate' : 'SearchResultEngine.importTemplate'}
        </TextWidget>
      </Button>
      <input ref={inputRef} type="file" accept='.jsx' onChange={onUploadTemplate} style={{ display: 'none' }} />
      {/* {isUploadUrl && (
        <div className="downloadUploadTemplate">
          <img src={jgmb} />
          <p>
            {value?.name} <DownloadOutlined onClick={() => onDownloadTemplate()} />
          </p>
        </div>
      )} */}
      {value && <div className="downloadUploadTemplate">
        <img src={jgmb} />
        <p>
          {value?.name} <DownloadOutlined onClick={() => onDownloadTemplate()} />
        </p>
      </div>}
    </div>
  );
}
